﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using Foreglance.MVP.Delegates;
using Foreglance.MVP.Presenters;
using Foreglance.MVP.Views;

namespace Foreglance.MVP.Views.Mediators
{
    public abstract class AbstractMediator: IMediator
    {
        public event ObjectEventHandler<IView> OnViewAdded;
        public event ActionEventHandler OnActivate;
        public void Activate()
        {
            if (OnActivate != null)
                OnActivate();
        }

        protected AbstractMediator()
        {
            var mediatorForm = new MediatorForm();
            mediatorForm.Load += (s, e) => Init();
            OnViewAdded += (view) => AddView(view, mediatorForm.Controls);
            OnActivate += mediatorForm.Show;
        }

        private static void AddView(IView view, Control.ControlCollection controls)
        {
            var viewControl = (Control) view;
            viewControl.Dock = DockStyle.Top;
            controls.Add(viewControl);
        }

        private readonly Dictionary<Type, IViewPresenter> _presenters = new Dictionary<Type, IViewPresenter>();

        public T GetView<T>()
        {
            var type = typeof(T);
            return _presenters.ContainsKey(type) ? (T)_presenters[type] : default(T);
        }

        public void Init()
        {
            SetupViews();
            foreach (IViewPresenter presenter in _presenters.Values)
            {
                presenter.Init();
            }
            foreach (IViewPresenter presenter in _presenters.Values)
            {
                presenter.Begin();
            }
        }

        protected abstract void SetupViews();

        public void AddView(IViewPresenter viewPresenter)
        {
            _presenters.Add(viewPresenter.GetType(), viewPresenter);
            if (OnViewAdded != null)
                OnViewAdded(viewPresenter.View);
        }
    }
}
